package leetcode.leetcode_3446;

import java.util.ArrayList;
import java.util.Comparator;

class Solution {
    private int[][] ans;
    private int n;
    private int m;

    public int[][] sortMatrix(int[][] grid) {
        n = grid.length;
        m = grid[0].length;
        ans = new int[n][m];
    // 找到右下角起点
    for (int i = 0 ; i < n; i++){
        sort(i , 0 , true , grid);
    }
    for (int i = 1 ; i < m; i++){
        sort(0 , i , false , grid);
    }
    return ans;
    }

    /**
     * @Description: flag 为true时表示递减
     * @Param: [i, j, flag, grid]
     * @return: void
     * @Author: ahang
     * @Date: 2025/8/28
     */

    public void sort(int i, int j, boolean flag, int grid[][]) {
        ArrayList<Integer> list = new ArrayList<>();
        int i_temp = i;
        int j_temp = j;
        while (i < n && j < m) {
            list.add(grid[i][j]);
            i++;
            j++;
        }
      if (flag){
          list.sort((x,y)->Integer.compare(y,x));
      }
      else{
          list.sort(Integer::compareTo);
      }
      int index =0;
      while(i_temp < n && j_temp < m){
          ans[i_temp][j_temp] = list.get(index);
          i_temp++;
          j_temp++;
          index++;
      }
    }
}